package com.milkshopbackend.milkshop.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.milkshopbackend.milkshop.Service.ProductStatsService;
import com.milkshopbackend.milkshop.entity.OrderItem;
import com.milkshopbackend.milkshop.entity.Product;
import com.milkshopbackend.milkshop.entity.Review;
import com.milkshopbackend.milkshop.mapper.OrderItemMapper;
import com.milkshopbackend.milkshop.mapper.ProductMapper;
import com.milkshopbackend.milkshop.mapper.ReviewMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class ProductStatsServiceImpl implements ProductStatsService {

    private final ProductMapper productMapper;
    private final OrderItemMapper orderItemMapper;
    private final ReviewMapper reviewMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProductStats(Long productId, Integer rating, Integer quantity) {
        Product product = productMapper.selectById(productId);
        if (product == null) {
            log.error("商品不存在，productId: {}", productId);
            return;
        }

        // 更新销量
        product.setSales(product.getSales() + quantity);

        // 更新评分（计算平均分）
        if (rating != null) {
            // 获取该商品的所有评价
            LambdaQueryWrapper<Review> reviewWrapper = new LambdaQueryWrapper<>();
            reviewWrapper.eq(Review::getProductId, productId);
            List<Review> reviews = reviewMapper.selectList(reviewWrapper);

            // 计算平均分
            double avgRating = reviews.stream()
                    .mapToInt(Review::getRating)
                    .average()
                    .orElse(0.0);

            product.setRating((int) Math.round(avgRating));
        }

        productMapper.updateById(product);
    }

    /**
     * 订单完成时调用，只增加销量
     */
    public void updateProductSalesByOrder(Long orderId) {
        LambdaQueryWrapper<OrderItem> orderItemWrapper = new LambdaQueryWrapper<>();
        orderItemWrapper.eq(OrderItem::getOrderId, orderId);
        List<OrderItem> orderItems = orderItemMapper.selectList(orderItemWrapper);
        for (OrderItem orderItem : orderItems) {
            Product product = productMapper.selectById(orderItem.getProductId());
            if (product != null) {
                product.setSales(product.getSales() + orderItem.getQuantity());
                productMapper.updateById(product);
            }
        }
    }

    /**
     * 订单评价时调用，只更新评分
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProductStatsByOrder(Long orderId) {
        // 获取订单中的所有商品
        LambdaQueryWrapper<OrderItem> orderItemWrapper = new LambdaQueryWrapper<>();
        orderItemWrapper.eq(OrderItem::getOrderId, orderId);
        List<OrderItem> orderItems = orderItemMapper.selectList(orderItemWrapper);

        // 获取订单的评价
        LambdaQueryWrapper<Review> reviewWrapper = new LambdaQueryWrapper<>();
        reviewWrapper.eq(Review::getOrderId, orderId);
        List<Review> reviews = reviewMapper.selectList(reviewWrapper);

        // 只更新评分
        for (OrderItem orderItem : orderItems) {
            Review review = reviews.stream()
                    .filter(r -> r.getProductId().equals(orderItem.getProductId()))
                    .findFirst()
                    .orElse(null);
            if (review != null) {
                Product product = productMapper.selectById(orderItem.getProductId());
                if (product != null) {
                    // 计算平均分
                    LambdaQueryWrapper<Review> allReviewWrapper = new LambdaQueryWrapper<>();
                    allReviewWrapper.eq(Review::getProductId, product.getId());
                    List<Review> allReviews = reviewMapper.selectList(allReviewWrapper);
                    double avgRating = allReviews.stream()
                            .mapToInt(Review::getRating)
                            .average()
                            .orElse(0.0);
                    product.setRating((int) Math.round(avgRating));
                    productMapper.updateById(product);
                }
            }
        }
    }
} 